import { defineStore } from 'pinia';
import { store } from '/@/plugins/setupStore';

import { LoginParams, GetUserInfoModel } from '/@/model/user/userModel';
import { login as loginApi, refreshToken as refreshTokenApi } from '/@/api/system/user';

interface UserState {
  userInfo: UserInfo;
  token: string;
  refreshToken: string;
}

export const useUserStore = defineStore({
  id: 'user',
  state: (): UserState => ({
    userInfo: {},
    token: '',
    refreshToken: '',
  }),
  getters: {
    getUserInfo(): UserInfo {
      return this.userInfo;
    },
    getToken(): string {
      return this.token;
    },
    getRefreshToken(): string {
      return this.refreshToken;
    },
  },
  actions: {
    setToken(info: string | undefined) {
      this.token = info ? info : ''; // for null or undefined value
    },
    setRefreshToken(info: string) {
      this.refreshToken = info;
    },
    setUserInfo(info: UserInfo) {
      this.userInfo = info;
    },
    //刷新token
    async refreshTokens() {
      const userInfo = this.userInfo;
      const res = await refreshTokenApi({
        grant_type: 'refresh_token',
        scope: 'all',
        tenantId: userInfo.tenant_id,
        refresh_token: this.refreshToken
      });
      const { access_token, refresh_token } = res.data;
      const newUserInfo = res.data as any as UserInfo;
      this.setUserInfo(newUserInfo);
      // save token
      this.setToken(access_token);
      this.setRefreshToken(refresh_token);
    },
    resetState() {
      this.userInfo = {};
      this.token = '';
      this.refreshToken = '';
    },

    /**
     * @description: login
     */
    async login(
      params: LoginParams & {
        goHome?: boolean;
      }
    ): Promise<GetUserInfoModel | null> {
      try {
        const res = await loginApi(params);
        const {
          data: { access_token, refresh_token }
        } = res as any;
        // save token
        this.setToken(access_token);
        this.setRefreshToken(refresh_token);
        // set userinfo
        const userInfo = res.data as any as GetUserInfoModel;
        this.setUserInfo(userInfo);
        return userInfo;
      } catch (error) {
        return Promise.reject(error);
      }
    },


    /**
     * @description: 退出登录
     */
    logout() {
      this.setUserInfo({});
      this.setToken('');
      this.setRefreshToken('');
    }
  }
});

// Need to be used outside the setup
export function useUserStoreWithOut() {
  return useUserStore(store);
}
